package cn.xuanxuanyuhua.crm.service.impl;


import cn.xuanxuanyuhua.crm.domain.Permission;
import cn.xuanxuanyuhua.crm.mapper.PermissionMapper;
import cn.xuanxuanyuhua.crm.query.QueryObject;
import cn.xuanxuanyuhua.crm.service.IPermissionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;


@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ApplicationContext ctx;//获取容器对象


    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Permission> list = permissionMapper.queryForList(qo);
        return new PageInfo(list);
    }

    @Override
    public List<Permission> list() {
        return permissionMapper.selectAll();
    }


    /**
     * 权限加载
     */
    @Override
    public void reload() {
        //获取权限表中所有的权限表达式
        List<String> expressions = permissionMapper.selectExpression();
        //获取所有ControllerBean
        Collection<Object> ctrls = ctx.getBeansWithAnnotation(Controller.class).values();
        for (Object ctrl : ctrls) {
            //因为所有贴有权限注解的方法都会被代理,而且因为是类而不是接口所以使用Cglib代理
            if (AopUtils.isCglibProxy(ctrl)) {
                //获取父类的方法对象
                Method[] methods = ctrl.getClass().getSuperclass().getMethods();
                for (Method method : methods) {
                    //获取从贴有权限注解的方法对象上获取注解对象
                    RequiresPermissions annotation = method.getAnnotation(RequiresPermissions.class);
                    //如果注解为null并且权限表中没有该权限表达式,则保存
                    if (annotation != null && !expressions.contains(annotation.value()[1])) {
                        Permission permission = new Permission();
                        permission.setName(annotation.value()[0]);
                        permission.setExpression(annotation.value()[1]);
                        permissionMapper.insert(permission);
                    }
                }

            }
        }


    }

    @Override
    public void delete(Long id) {
        permissionMapper.deleteRelationByPermissionId(id);
        permissionMapper.deleteByPrimaryKey(id);
    }

}
